package com.imdroid.carac.process;

import java.util.ArrayList;
import java.util.Collection;

import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import com.baidu.location.BDLocation;
import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.model.Team;
import com.imdroid.carac.model.TeamMember;
import com.imdroid.carac.net.HttpHelper;
import com.imdroid.carac.services.UDPServer;

/**
 * The process of team
 * 
 */
public class TeamProcess extends BaseProcess {
	private static final String TAG = "TeamProcess";
	/**
	 * The thread of sending location
	 */
	private Thread locationThread;
	/**
	 * The list of the location
	 */
	private static volatile ArrayList<BDLocation> locations = new ArrayList<BDLocation>();

	/**
	 * Search the teams from the server
	 * 
	 * @param keyword
	 *            the keyword
	 * @return the collection the team member
	 * @throws Exception
	 */
	public Collection<Team> searchTeam(String keyword) throws Exception {
		// 从服务请请求好友列表
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("keyWord", keyword));
		params.add(new BasicNameValuePair("userId", IMDroid.getUser()
				.getUser_id() + ""));
		String message = HttpHelper.execute("SearchTeam", params).trim();

		// 解析返回字符串
		Collection<Team> teams = new ArrayList<Team>();
		if (message != null && message.length() > 0) {
			String[] items = message.split(";");
			for (String item : items)
				teams.add(Team.getTeam(item));
		}

		return teams;
	}

	/**
	 * Search the teams near by from the server
	 * 
	 * @param location
	 *            the location of the user
	 * @return the collection the team member
	 * @throws Exception
	 */
	public Collection<Team> searchTeamNearby(BDLocation location)
			throws Exception {
		if (location == null)
			throw new Exception(IMDroid.getContext().getResources()
					.getString(R.string.team_error_no_gps));

		// 从服务请请求好友列表
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("lat", location.getLatitude() + ""));
		params.add(new BasicNameValuePair("lon", location.getLongitude() + ""));
		String message = HttpHelper.execute("SearchTeamNearBy", params).trim();

		// 解析返回字符串
		Collection<Team> teams = new ArrayList<Team>();
		if (message != null && message.length() > 0) {
			String[] items = message.split(";");
			for (String item : items) {
				Team t = Team.getTeam(item);
				t.setTeamSource(Team.SOURCE_SEARCH);
				teams.add(t);
			}
		}
		return teams;
	}

	/**
	 * Get the access code of the target team
	 * 
	 * @param teamId
	 *            the id of the target team
	 * @return the access code of the target team
	 * @throws Exception
	 */
	public String getTeamAccessCode(long teamId) throws Exception {
		// 从服务器查询队伍进入的密码
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("teamId", teamId + ""));
		return HttpHelper.execute("GetTeamAccessCode", params).trim();
	}

	/**
	 * Join the team
	 * 
	 * @param team
	 *            the team join to
	 * @return success or not
	 * @throws Exception
	 */
	public boolean joinTeam(Team team) throws Exception {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("teamId", team.getTeamId() + ""));
		params.add(new BasicNameValuePair("userId", IMDroid.getUser()
				.getUser_id() + ""));
		String message = HttpHelper.execute("i/TeamJoin", params).trim();
		Team.setCurrentTeam(team);
		Log.d(TAG, "TEAM...." + Team.getCurrentTeam());
		String[] items = message.split(":");
		if (items.length > 1)
			team.setTeamName(items[1]);
		if (items.length > 2)
			team.setDestinationName(items[2]);
		if (items.length > 3)
			team.setDestinationLat(Float.parseFloat(items[3]));
		if (items.length > 4)
			team.setDestinationLon(Float.parseFloat(items[4]));
		if (items.length > 5)
			team.setSearchRoute(items[5].trim().equals("1"));

		return "1".equals(message);
	}

	/**
	 * Refresh the team member
	 * 
	 * @param team
	 *            The team
	 * @return success or not
	 * @throws Exception
	 */
	public boolean refreshTeamMember(Team team) throws Exception {
		if (team == null)
			return false;
		team.getMembers().clear();

		// 从服务请请求好友列表
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("teamId", team.getTeamId() + ""));
		String message = HttpHelper.execute("TeamMember", params).trim();

		// 解析返回字符串
		if (message != null && message.length() > 0) {
			String[] items = message.split(";");
			for (String item : items)
				team.addTeamMember(TeamMember.getTeamMember(item));
		}

		return true;
	}

	/**
	 * Exit from current team
	 * 
	 * @return return success or not
	 * @throws Exception
	 */
	public boolean exitTeam() throws Exception {
		if (Team.getCurrentTeam() == null)
			return false;
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("userId", IMDroid.getUser()
				.getUser_id() + ""));
		params.add(new BasicNameValuePair("teamId", Team.getCurrentTeam()
				.getTeamId() + ""));
		String message = HttpHelper.execute("/i/TeamExit", params).trim();
		Team.setCurrentTeam(null);
		return "1".equals(message);
	}

	/**
	 * dismiss the team
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean dismissTeam() throws Exception {

		if (Team.getCurrentTeam() == null)
			return false;

		if (IMDroid.getUser().getUser_id() != Team.getCurrentTeam().getTeamId())
			return false;

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("userId", IMDroid.getUser()
				.getUser_id() + ""));
		params.add(new BasicNameValuePair("teamId", Team.getCurrentTeam()
				.getTeamId() + ""));
		String message = HttpHelper.execute("/i/TeamCancel", params).trim();
		return "1".equals(message);
	}

	public boolean kickOff(int userNumber) {
		return true;
	}

	/**
	 * Sent the team destination
	 * 
	 * @param team
	 *            the target team
	 * @return success or not
	 * @throws Exception
	 */
	public boolean sendTeamDestination(Team team) throws Exception {
		if (team == null)
			return false;

		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("userId", IMDroid.getUser()
				.getUser_id() + ""));
		params.add(new BasicNameValuePair("teamId", team.getTeamId() + ""));
		params.add(new BasicNameValuePair("destination", team
				.getDestinationName() != null ? team.getDestinationName()
				.trim() : ""));
		params.add(new BasicNameValuePair("teamDestinationLon", team
				.getDestinationLon() + ""));
		params.add(new BasicNameValuePair("teamDestinationLat", team
				.getDestinationLat() + ""));
		params.add(new BasicNameValuePair("routeSearch",
				team.isSearchRoute() ? "1" : "0"));

		String message = HttpHelper.execute("/i/TeamDestination", params)
				.trim();
		return "1".equals(message);
	}

	/**
	 * Sending the location
	 * 
	 * @param location
	 *            sending the location
	 * @return success nor not
	 * @throws Exception
	 */
	public boolean sendLocation(BDLocation location) {
		// 如果线程还没有启动，则启动线程
		if (locationThread == null) {
			Log.d(TAG, "Thread start---");
			locationThread = new Thread(new LocationRunnable());
			locationThread.start();
		}
		synchronized (locations) {
			Log.d(TAG, "Send---");
			locations.add(location);
			locations.notify();
		}
		return true;

	}

	/**
	 * The runable of sending the location
	 * 
	 */
	private class LocationRunnable implements Runnable {
		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		public void run() {

			try {
				Thread.sleep(10000);
			} catch (Exception e) {
				e.printStackTrace();
			}

			BDLocation location = null;
			while (true) {
				synchronized (locations) {
					while (locations.size() == 0) {
						try {
							locations.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					// Send the latest location ONLY
					location = locations.get(locations.size() - 1);
					locations.clear();
				}
				try {
					send(location);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}

		/**
		 * Set the location to other team member
		 * 
		 * @param location
		 *            the current location of device
		 * @throws Exception
		 */
		private boolean send(BDLocation location) throws Exception {
			if (Team.getCurrentTeam() == null)
				return false;
			UDPServer.sendTeamLocation(location);
			return true;
		}
	}
}
